package psn.james.kaixin.module;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import psn.james.kaixin.KaiXinFarm;
import psn.james.kaixin.po.Friend;
import psn.james.kaixin.util.Network;

public class StayHouse extends Thread{

	@Override
	public void run() {
		System.out.println("trying to change house...");
		boolean succeed;
		long sleepTime;
		
		while(true){
			succeed = false;
			for(Friend friend : KaiXinFarm.FRIENDLIST){
				succeed = stayHouse(friend);
				if(succeed){
					System.out.println("house has changed to " + friend.getUserName());
					break;
				}
			}
			sleepTime = succeed?61*60*1000:1*60*1000;
			try {
				sleep(sleepTime);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private boolean stayHouse(Friend toFriend){
		String baseURL = Network.KAIXINNETWORK + "/house/stayhouse.php?";
		String url = baseURL +
			"verify=" + KaiXinFarm.VERIFYCODE + 
			"&tuid=" + toFriend.getUid() +
			"&roomid=" + toFriend.getRoomId() +
			"&fuid=" + KaiXinFarm.UID +
			"&status=0";
		
		String resp = Network.callURL(url, KaiXinFarm.COOKIES);
		return checkResult(resp);
	}
	
	private boolean checkResult(String resp){
		String flag = "";
		String regex = "(stayhouse_ret|stayhouse_newret)\\(\\d+?,\\d+?,(\\d{1}),.+?\\)";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(resp);
		if(m.find())
			flag = m.group(2);
		
		return "0".equals(flag);
	}
}
